package cn.ydxiaoshuai.util;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author 小帅丶
 * @className DealDataUtil
 * @Description 处理数据工具类
 * @Date 2021-07-08-10:34
 **/
@Slf4j
public class DealDataUtil extends JFrame{
    private static final long serialVersionUID = 1L;
    private static JLabel label;
    private static Icon icon;

    /**
     * 把图片加载到JFrame窗口
     * @Author 小帅丶
     * @description 把图片加载到JFrame窗口
     * @Date  2021-07-08 10:56
     * @param base64 - 图片的BASE64编码内容
     * @param title - 窗口名称
     * @return void
     **/
    public static void drawImageToFrame(String base64,String title){
        JFrame jFrame = new JFrame();
        try {
            BufferedImage bufferedImage = base64ToBufferedImage(base64);
            if(null!=bufferedImage){
                jFrame.setTitle(title);
                jFrame.setSize(400,400);
                label = new JLabel();
                icon = new ImageIcon(bufferedImage);
                label.setIcon(icon);
                jFrame.getContentPane().add(new JScrollPane(label));
                jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                jFrame.setVisible(true);
            }else{
                log.info("图片转换失败");
            }
        }catch (Exception e){
            log.info("drawImageToFrame() 出错了{}",e.getMessage());
        }
    }

    /**
     * 把图片加载到JFrame窗口
     * @Author 小帅丶
     * @description 把图片加载到JFrame窗口
     * @Date  2021-07-08 10:56
     * @param base64 - 图片的BASE64编码内容
     * @return void
     **/
    public static void drawImageToFrame(String base64){
        drawImageToFrame(base64,"预览图");
    }


    /**
     * base64 编码转换为 BufferedImage
     * @Author 小帅丶
     * @Description base64 编码转换为 BufferedImage
     * @Date  2021-07-08 10:55
     * @param base64 - 图片的BASE64编码内容
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage base64ToBufferedImage(String base64) {
        try {
            byte[] bytes = Base64.decode(base64);
            ByteArrayInputStream byteArrayInputStream
                    = new ByteArrayInputStream(bytes);
            return ImageIO.read(byteArrayInputStream);
        } catch (IOException e) {
            log.info("base64ToBufferedImage() 出错了{}", e.getMessage());
            return null;
        }
    }

}
